package com.pds.system.service.impl;

import com.pds.common.core.domain.entity.SysDept;
import com.pds.common.core.domain.model.LoginUser;
import com.pds.common.utils.DateUtils;
import com.pds.common.utils.DeptUtils;
import com.pds.common.utils.SecurityUtils;
import com.pds.common.utils.StringUtils;
import com.pds.common.utils.minio.MinioUtils;
import com.pds.common.utils.uuid.UUID;
import com.pds.system.domain.FileUpload;
import com.pds.system.mapper.FileUploadMapper;
import com.pds.system.service.IFileUploadService;
import io.minio.ObjectWriteResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.Date;
import java.util.List;

/**
 * 文件上传Service业务层处理
 *
 *
 * @date 2024-03-26
 */
@Service
@Slf4j
public class FileUploadServiceImpl implements IFileUploadService
{
    @Autowired
    private FileUploadMapper fileUploadMapper;
    @Autowired
    private MinioUtils minioUtils;

    /**
     * 文件别头
     */
    private static final String FILE_CODE = "F";


    /**
     * 根据文件ID集合查询文件列表
     *
     * @param ids
     * @return 文件上传集合
     */
    public List<FileUpload> selectFileUploadListByIds(String ids){
        log.info("根据文件ID集合查询文件列表 入参: "+ids);
        if (StringUtils.isEmpty(ids)){
            return null;
        }
        ids.replace("，",",");
        String[] id=ids.split(",");
        return fileUploadMapper.selectFileUploadListByIds(id);
    }


    /**
     * 上传文件并返回文件id
     * @param file
     * @param filesType 默认永久保存，1可以过期
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public FileUpload uploadAndReturnFileID(MultipartFile file,String filesType) throws Exception{
        // 获取当前的用户信息
        LoginUser currentUser = SecurityUtils.getLoginUser();
        //获取二级部门id
        String userId=String.valueOf(currentUser.getUser().getUserId());
        String userName=String.valueOf(currentUser.getUser().getNickName());
        String deptName=String.valueOf(currentUser.getUser().getDept().getDeptName());
        String deptId=String.valueOf(currentUser.getUser().getDept().getDeptId());
        //获取源文件名称
        String fileId= FILE_CODE+UUID.fastUUID().toString().replaceAll("-","");
        String originalFileName = file.getOriginalFilename();
        int extIndex = originalFileName.lastIndexOf(".");
        String ext = originalFileName.substring(extIndex,originalFileName.length());
        String saveName=fileId+ext;
        //使用当前年+顶级部门id，用于区分，将企业、机构、环保局的文件放入不同的桶中
        String path= DateUtils.getYearNow() + DeptUtils.getSecondLevelDeptId(currentUser.getUser().getDept(),2)+"/";
        String type = "0";
        if("1".equals(filesType)){
            path = "temp/"+path;
            type = "1";
        }else{
            path = "storage/"+path;
        }
        String fileSize=minioUtils.readableFileSize(file.getSize());
        String bucketName = "enviroment";
        //上传文件
        String url = minioUtils.putObject(file, path+saveName, bucketName);
        if(null!=url){
            FileUpload fileUpload = new FileUpload();
            fileUpload.setAttachmentId(fileId);
            fileUpload.setFileName(originalFileName);
            fileUpload.setFileSaveName(saveName);
            fileUpload.setBucketname(bucketName);
            fileUpload.setUploadTime(new Date());
            fileUpload.setFileSize(fileSize);
            fileUpload.setUploadUser(userName);
            fileUpload.setUploadUserId(userId);
            fileUpload.setUploadDeptId(deptId);
            fileUpload.setUploadDept(deptName);
            fileUpload.setExtensionField1(type); // 0长期存储，1可以过期
            int index = url.indexOf("//");
            String pathUrl = url.substring(index+2);
            index = pathUrl.indexOf("/");
            String tempUrl = pathUrl.substring(index);
            index = tempUrl.indexOf("?");
            url = tempUrl.substring(0,index);
            fileUpload.setUrl(url);
            fileUploadMapper.insertFileUpload(fileUpload);
            return fileUpload;
        }else {
            return  null;
        }
    }

    /**
     * 查询文件上传
     *
     * @param attachmentId 文件上传ID
     * @return 文件上传
     */
    @Override
    public FileUpload selectFileUploadById(String attachmentId)
    {
        return fileUploadMapper.selectFileUploadById(attachmentId);
    }


    /**
     * 根据桶名和文件名下载
     * @param bucketName
     * @param objectName
     * @return
     */
    @Override
    public InputStream downLoadInfoByName(String bucketName, String objectName) {
        InputStream inputStream=  minioUtils.getObject(bucketName, objectName);
        return inputStream;
    }


    /**
     * 新增文件上传
     *
     * @param fileUpload 文件上传
     * @return 结果
     */
    @Override
    public int insertFileUpload(FileUpload fileUpload)
    {
        return fileUploadMapper.insertFileUpload(fileUpload);
    }

    /**
     * 修改文件上传
     *
     * @param fileUpload 文件上传
     * @return 结果
     */
    @Override
    public int updateFileUpload(FileUpload fileUpload)
    {
        return fileUploadMapper.updateFileUpload(fileUpload);
    }

    /**
     * 批量删除文件上传
     *
     * @param attachmentIds 需要删除的文件上传ID
     * @return 结果
     */
    @Override
    public int deleteFileUploadByIds(String[] attachmentIds)
    {
        return fileUploadMapper.deleteFileUploadByIds(attachmentIds);
    }

    /**
     * 删除文件上传信息
     *
     * @param attachmentId 文件上传ID
     * @return 结果
     */
    @Override
    public int deleteFileUploadById(String attachmentId)
    {
        return fileUploadMapper.deleteFileUploadById(attachmentId);
    }







}

